<?php

/**
 * Description of PublicController
 *
 * @author Poh Nean
 * Modify Duong
 */
class PublicController extends Controller
{

	public $layout = '/public/layout';

	/**
	 * @var Agency the agency
	 */
	public $agency;

	public function filters()
	{
		return CMap::mergeArray(parent::filters(), array(
					'agencyContext'
		));
	}

	public function filterAgencyContext(CFilterChain $filterChain)
	{
		if (isset($_GET['agency_id'])) {
			$this->agency = Agency::model()->findByAttributes(array('id' => $_GET['agency_id']));
		}

		// check module
		if ($this->agency !== null) {
			if ($this->agency->checkModuleAccess('Propsage.TicketManagement') === false) {
				throw new PsPageNotFoundException();
			}
		} else {
			throw new PsPageNotFoundException();
		}

		$filterChain->run();
	}

	/**
	 * Site controller access rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow all users
				'users' => array('*'),
			),
		);
	}

	public function actionIndex()
	{
	//var_dump($_SESSION);exit;
		if (!isset(Yii::app()->session['ticket_code'])) {
			$ticket = new UserLogin;
			
			//UserLogin
			//$_GET[];
			//$_GET[];
			if (isset($_POST['UserLogin'])) {
				//echo 'ss';exit;
				$ticket->attributes = $_POST['UserLogin'];
				//dump($_POST['UserLogin']);exit;
				if($ticket->validate()){
				//dump($_POST['Ticket']);exit;
					$userTicket = TicketClient::model()->findByAttributes(array(
						'email' => $_POST['UserLogin']['email'],
						'ticket_code' => $_POST['UserLogin']['ticket_code']
					));
					//dump($userTicket);exit;
					if ($userTicket === null) {
						
						PsSystemMessage::add('Ticket not found.', 'error', false);
					} else {
						Yii::app()->session['ticket_code'] = $_POST['UserLogin']['ticket_code'];
						Yii::app()->session['email'] = $_POST['UserLogin']['email'];
						$this->redirect(array('public/list', 'ticket_code' => $userTicket->ticket_code, 'email' => $userTicket->email, 'agency_id' => $this->agency->id));
					}
				}	
			}

			$data = array();
			$data['ticket'] = $ticket;
			$this->render('index', $data);
		}
		else {
			$this->redirect(array('public/list/ticket_code/'.Yii::app()->session['ticket_code'].'/email/'.Yii::app()->session['email'].'/agency_id/4091'));
		}
	}

	public function actionOpen()
	{
		$ticket = new Ticket;
		$agency_id = $_GET['agency_id'];
		//echo $agency_id;exit;
		//echo 'ddd';exit;
		if (isset($_POST['Ticket'])) {
			$ticket->agency_id =$agency_id;
			$ticket->attributes = $_POST['Ticket'];
			$ticket->ticket_source_id = 5;
			$ticket->ticket_priority_id = 2;
			$ticket->ticket_code = uniqid(time() . rand(10*45, 100*98));
			$ticket->ticket_client_id = time() . rand(10*45, 100*98);
			
			$isValid = $ticket->validate();
			if ($isValid) {
				$tx = Yii::app()->db->beginTransaction();

				try {
					$ticket->save(false);
					
					$ticketClient = new TicketClient;
					
					$ticketClient->email = $ticket->email;
					$ticketClient->ticket_code = $ticket->ticket_code;
					$ticketClient->save(false);
					
					$ticketStatus = new TicketStatusHistory;
					$ticketStatus->ticket_status_type_id = 1;
					$ticketStatus->ticket_id = $ticket->id;
					$ticketStatus->change_by_ticket_client_id = $ticketClient->id;
					$ticketStatus->update_time = new CDbExpression('UTC_TIMESTAMP()');
					$ticketStatus->save(false);

					
					
					$tx->commit();
					
					//$success = $ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_NEW);
					$mails = new MailHelper;
					$message = $mails->createTicket($ticket->ticket_code);
					$to = $ticket->email;
					$headers = "From: " . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'Reply-To:' . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'X-Mailer: PHP/' . phpversion();
					$headers .= 'MIME-Version: 1.0' . "\r\n";
					$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
					mail( $to  , 'New Ticket', $message , $headers);
					
					
					PsSystemMessage::add('Ticket #' . $ticket->ticket_code . ' submitted. You can use this code and your email to view feedback latterly', 'success', false);
					$this->redirect(array('public/index', 'agency_id' => $agency_id));
				} catch (CDbException $e) {
					$tx->rollback();
//					dump($e);
				}
			} else {
//				dump($ticket->getErrors());
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$data['agency_id'] = $agency_id;
		$this->render('create', $data);
	}

	public function actionUpdate($ticket_code, $email)
	{
		$ticket = $this->loadTicket($ticket_code, $email);

		if (isset($_POST['Ticket'])) {
			$ticket->attributes = $_POST['Ticket'];
			$isValid = $ticket->validate();

			if ($isValid) {
				$tx = Yii::app()->db->beginTransaction();

				try {
					$ticket->save(false);

					$tx->commit();
					
					$mails = new MailHelper;
					$message = $mails->updateTicket($ticket);
					$to = $ticket->email;
					$headers = "From: " . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'Reply-To:' . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'X-Mailer: PHP/' . phpversion();
					$headers .= 'MIME-Version: 1.0' . "\r\n";
					$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
					mail( $to  , 'Update Ticket', $message , $headers);
					
					$this->redirect(array('public/index', 'agency_id' => $this->agency->id));
					PsSystemMessage::add('Ticket updated.', 'success');
				} catch (CDbException $e) {
					$tx->rollback();
				}
			} else {
				
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$this->render('update', $data);
	}

	public function actionList($ticket_code, $email)
	{
		//echo Yii::app()->user->isGuest.'ddd';
		
		if(isset(Yii::app()->session['ticket_code'])){
			//if (isset($_SESSION);exit;
				$userTicket = $this->loadTicket($ticket_code, $email);
				//dump($userTicket);exit;
				
					$ticket = new Ticket('search');
					$ticket->unsetAttributes();
					$ticket->email = $userTicket->email;
					$ticket->agency_id = $_GET['agency_id'];;
					//$ticket->agency_id = $userTicket->agency_id;
					
					//dump($ticket); exit;
					
					
					//$ticket->current_status = $ticket_status;
				//	dump($ticket); exit;
					if (isset($_GET['Ticket'])) {
						$ticket->attributes = $_GET['Ticket'];
						//$ticket->agency_id = $userTicket->agency_id;
					}

					$data = array();
					$data['ticket'] = $ticket;
					//$data['ticketStatusTypes'] = TicketStatusType::model()->findAll(array('order' => 'is_closing_status ASC'));

					$this->render('list', $data);
		}else {
			$this->redirect(array('/tickets/public/index', 'agency_id' => $this->agency->id));
		}
		
	}

	public function actionView($ticket_code, $email)
	{
		if(isset(Yii::app()->session['ticket_code'])){
			
			$ticket = $this->loadTicket($ticket_code, $email);
			
			$newTicketResponse = new TicketResponse;

			if (isset($_POST['TicketResponse'])) {
				$newTicketResponse->ticket_id = $ticket->id;
				$newTicketResponse->agency_id = $ticket->agency_id;
				$newTicketResponse->responded_by_email = $email;

				$newTicketResponse->update_time = new CDbExpression('UTC_TIMESTAMP()');
				$newTicketResponse->attributes = $_POST['TicketResponse'];

				if ($newTicketResponse->validate()) {
					$tx = Yii::app()->db->beginTransaction();
					try {
						if (isset($_POST['Ticket'])) {
						
							$Status = TicketStatusHistory::model()->findByAttributes(array('ticket_id'=>$ticket->id),array('order'=>'update_time DESC'));
							$oldType = $Status->ticket_status_type_id;
							
							if ($_POST['alsoChangeStatus'] == 1) {
								//$ticket->current_status = $_POST['Ticket']['current_status'];
								$newType = $_POST['Ticket']['ticket_type_id'];
								
								if ($newType != $oldType) {
									$ticketStatus = new TicketStatusHistory;
									
									$ticketStatus->ticket_status_type_id = $newType;
									$ticketStatus->ticket_id = $ticket->id;
									$ticketStatus->update_time = new CDbExpression('UTC_TIMESTAMP()');
									$ticketStatus->change_by_ticket_client_id =  $ticket->id;
									
									$ticketStatus->save(false);
								}

								$ticket->save(false);
							}
						}
						
						$newTicketResponse->save(false);
						
						//$ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_UPDATED, array('response' => $newTicketResponse->message));

						$tx->commit();

						$this->refresh();
					} catch (CDbException $e) {
						$tx->rollback();
					}
				}
			}

			$data = array();
			$data['ticket'] = $ticket;
			$data['newTicketResponse'] = $newTicketResponse;
			$this->render('view', $data);
		} else{
			$this->redirect(array('/tickets/public/index', 'agency_id' => $this->agency->id));
		}
	}

	/**
	 * @param string $ticket_code
	 * @return Ticket
	 * @throws PsPageNotFoundException
	 */
	public function actionLogout(){
		Yii::app()->session->destroy();
		$this->redirect(array('/tickets/public/index', 'agency_id' => $this->agency->id));
	}
	public function loadTicket($ticket_code, $email)
	{
		$ticket = Ticket::model()->findByAttributes(array(
			'ticket_code' => $ticket_code,
			'email' => $email,
			//'agency_id' => $this->agency->id
		));

		if ($ticket === null) {
			throw new PsPageNotFoundException();
		}

		return $ticket;
	}

}

?>
